package provider

import (
	"context"
	"go-caipu/pkg/plugins"
	"go-caipu/pkg/plugins/backendplugin"
	"go-caipu/pkg/plugins/backendplugin/coreplugin"

	"go-caipu/pkg/plugins/backendplugin/grpcplugin"
)

// PluginBackendProvider is a function type for initializing a Plugin backend.
type PluginBackendProvider func(_ context.Context, _ *plugins.Plugin) backendplugin.PluginFactoryFunc

type Service struct {
	providerChain []PluginBackendProvider
}

func New(providers ...PluginBackendProvider) *Service {
	if len(providers) == 0 {
		return New(DefaultProvider)
	}
	return &Service{
		providerChain: providers,
	}
}

func ProvideService(coreRegistry *coreplugin.Registry) *Service {
	return New(coreRegistry.BackendFactoryProvider(), DefaultProvider)
}
func (s *Service) BackendFactory(ctx context.Context, p *plugins.Plugin) backendplugin.PluginFactoryFunc {
	for _, provider := range s.providerChain {
		if factory := provider(ctx, p); factory != nil {
			return factory
		}
	}
	return nil
}

var DefaultProvider PluginBackendProvider = func(_ context.Context, p *plugins.Plugin) backendplugin.PluginFactoryFunc {
	return grpcplugin.NewBackendPlugin(p.ID, p.ExecutablePath())
}
